<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Core_Db_Entity extends Core_Entity {

	protected $_conn = null;
	
	protected $_table = '';

	protected $_idFieldName = 'id';
	
	public function __construct($conn = null) {
		$this->_conn = $conn;
	}

	public function setBaseTable($table) {
		$this->_table = $table;
	}
	
	public function getIdFieldName() {
		return $this->_idFieldName;
	}

	public function getId() {
		return $this->getData($this->_idFieldName);
	}

	public function setId($val) {
		return $this->setData($this->_idFieldName, $val);
	}
	
	public function save() {
		$this->_beforeSave();
		$isUpdate = $this->getId()>0;
		if ($isUpdate) {    // update
			$this->_conn->where($this->_idFieldName, $this->getId());
			$data = $this->getData();
			unset($data[$this->_idFieldName]);
			$this->_conn->update($this->_table, $data); 
		} else {    // insert
			$this->_conn->insert( $this->_table, $this->getData() );
			$this->_data[$this->_idFieldName] = $this->_conn->insert_id();
		}
		$this->_afterSave($isUpdate);
		$this->_settedField = array();
	}
	
	public function load($id) {
		$query = $this->_conn->get_where( $this->_table, array($this->_idFieldName => $id) );
		$this->addData($query->first_row(0));
		return $this;
	}
	
	public function delete() {
		if ($this->getId()) {
			$this->_beforeDelete();
			$this->_conn->delete($this->_table, array($this->_idFieldName => $this->getId())); 
		}
	}
	
	public function getCollection() {
		$className = get_class($this) . '_Collection';
		$file = APPPATH . 'libraries/' . str_replace('_', '/', $className) . '.php';

		if (file_exists($file))	include_once $file;
		if (!class_exists($className))
			$className = 'Core_Db_Collection';
		
		$res = App::object($className, App::db());
		$res->setItemClass(get_class($this));
		$res->setBaseTable($this->_table);
		return $res;
	}
	
	protected function _beforeSave() {}

	protected function _afterSave($isUpdate) {}
	
	protected function _beforeDelete() {}
}